<?php


namespace app\shop\service;



use app\dao\shop\ShopDao;
use app\dao\user\ShopUserDao;
use app\lib\exception\AuthException;
use app\utils\JWT;
use plugins\wx\miniprogram\WXMiniLogin;
use think\facade\Cache;



class AuthService
{
    public function login($shopName, $js_code)
    {
        $shopUserDao = new ShopUserDao();
        $shopDao = new ShopDao();

        $shop = $shopDao->getIdByName($shopName);

        $WXMiniLogin = app()->make(WXMiniLogin::class);

        $openid = $WXMiniLogin->jscode2session($js_code);


        $user = $shopUserDao->getByShopIdAndOpenId($shop->id, $openid);

        if ($user == null)
        {
            throw new AuthException();
        }
        if ($user->is_ban == 1)
        {
            throw new AuthException('账号被禁用');
        }

//        生成token
        $token = JWT::create($user->id);

        $this->setToken($token, $user);

        return $token;
    }

    public function setToken($token, $user)
    {
        Cache::store('redis')->set($token, $user, config('jwt.exp'));
    }

    public function getToken($token)
    {
        return Cache::store('redis')->get($token);
    }



}